var config = {
    leftSidebarSlideSpeed: 200
}
var anchor = $(".ayi-sidebar-elements li a");
var leftSidebar = $(".ayi-left-sidebar");
var openSidebar = false;
anchor.click(function (event) {
    var $el = $(this), $open;
    var $li = $el.parent();
    var $subMenu = $el.next();
    var isFirstLevel = $el.parents().eq(1).hasClass('ayi-sidebar-elements');
    $open = $li.siblings(".open");
    if ($li.hasClass('open')) {
        closeSubMenu($subMenu, event);
    } else {
        openSubMenu(this, event);
    }
    if ($el.next().is('ul')) {
        event.preventDefault();
    }
});

function closeSubMenu(subMenu, event) {
    var target = $(event.currentTarget);
    var li = $(subMenu).parent();
    if (!li.hasClass("ayi-parent-menu")) {
        return;
    }
    var openChildren = $('li.open', li);
    var clickOutside = !target.closest(leftSidebar).length;
    var slideSpeed = config.leftSidebarSlideSpeed;
    var isFirstLevel = target.parents().eq(1).hasClass('ayi-sidebar-elements');
    if ((isFirstLevel || clickOutside)) {
        li.removeClass('open');
        subMenu.removeClass('visible');
        openChildren.removeClass('open').removeAttr('style');
    } else {
        li.removeClass('open');
        $(this).removeAttr('style');
        openChildren.removeClass('open').removeAttr('style');
    }
}

function openSubMenu(anchor, event) {
    var _el = $(anchor);
    var li = $(_el).parent();
    if (!li.hasClass("ayi-parent-menu")) {
        return;
    }
    var subMenu = $(_el).next();
    var slideSpeed = config.leftSidebarSlideSpeed;
    var isFirstLevel = $(event.currentTarget).parents().eq(1).hasClass('sidebar-elements');
    var openSubMenus = li.siblings('.open');
    if (openSubMenus) {
        closeSubMenu($('> ul', openSubMenus), event);
    }
    if (isFirstLevel) {
        li.addClass('open');
        subMenu.addClass('visible');
    } else {
        li.addClass('open');
        $(this).removeAttr('style');
    }
}

$(".ayi-nav-menu").click(function () {
   $(".ayi-left-sidebar").toggle(3000);
});